<?php

namespace App\Admin\Forms\Project;

use App\Services\MaterialService;
use Dcat\Admin\Contracts\LazyRenderable;
use Dcat\Admin\Http\JsonResponse;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Admin;
use Illuminate\Support\Str;


class MaterialForm extends Form implements LazyRenderable
{
    use LazyWidget;

    /**
     * Handle the form request.
     *
     * @param array $input
     *
     * @return JsonResponse
     * @throws \App\Exceptions\AdminInvalidRequestException
     */
    public function handle(array $input): JsonResponse
    {
        //上传文件
        app(MaterialService::class)->upload($this->payload['id'], $input['material']);
        return $this
            ->response()
            ->success('资料上传成功')
            ->refresh();
    }

    /**
     * Build a form here.
     */
    public function form()
    {
        $this->multipleFile('material', '资料')
            ->rules('mimes:zip,rar,7z,tar,gz')
            ->autoUpload()
            ->required()
            ->removable()
            ->retainable()
            ->maxSize(1024 * 80)
            ->move('files/' . now()->year . '/' . now()->month . '/' . now()->day . '/' . Str::random(10))
            ->limit(50)
            ->help('支持格式：zip,rar,7z,tar,gz')
            ->saving(function ($files) {
                foreach ($files as $file) {
                    // 注意这里获取的是上传后的文件名，而不是文件原始名
                    $originalName = basename($file);
                    Admin::script("console.log('{$originalName}')");
                }

                return $files;
            });
    }

}
